package com.blockmeta.bbs.businesslibrary.util;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import androidx.annotation.RequiresPermission;
import androidx.core.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.blockmeta.bbs.baselibrary.base.app.BaseApp;

/**
 * @author AirThor
 * @date 2019/6/17.
 */
public class DeviceUtil {
    /**
     * 获取设备号
     *
     * @return
     */
    @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
    public static String getDeviceIMEI() {
        TelephonyManager telephonyManager = (TelephonyManager) BaseApp.getApp().getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            String imei;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                imei = telephonyManager.getImei();
            } else {
                imei = telephonyManager.getDeviceId();
            }
            return imei;
        }
        return "";
    }

    /**
     * 获取设备号
     *
     * @return
     */
    public static String getIMEI() {
        String imei;
        try {
            if (ActivityCompat.checkSelfPermission(BaseApp.getApp(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                imei = getDeviceIMEI();
            } else {
                imei = Settings.System.getString(BaseApp.getApp().getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        } catch (Exception e) {
            imei = "";
        }
        //部分手机获取imei会返回null，导致奔溃
        if(TextUtils.isEmpty(imei)){
            imei = Settings.System.getString(BaseApp.getApp().getContentResolver(), Settings.Secure.ANDROID_ID);
            if(imei == null){
                imei = "";
            }
        }
        return imei;
    }

    /**
     * 联网失败 打开系统设置联网
     *
     * @param context
     */
    public static void startWirelessSetting(Context context) {
        if (null == context) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //3.0以上打开设置界面
            context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
        } else {
            context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
        }
    }
}
